import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import store from '../store'
// 创建axios实例
axios.defaults.headers.post['Content-Type'] = 'application/json';
let service
if (process.env.NODE_ENV == "production") {
  let baseURL = window.location.origin + '/mgt-service/api';
  service = axios.create({
    baseURL: baseURL, // api的base_url
    timeout: 15000                  // 请求超时时间2
  })
} else {
  service = axios.create({
    baseURL: process.env.BASE_URL, // api的base_url
    timeout: 15000                  // 请求超时时间2
  })
}

// request拦截器
service.interceptors.request.use(config => {
  if (getToken()) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.Authorization = getToken();
  }

  return config
}, error => {
  // Do something with request error
  console.error(error) // for debug
  Promise.reject(error)
})
// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.errorCode == '200') {
      return res;
    } else if (res.errorCode == "504") {
      // store.dispatch('GetAutoToken').then(() => {
      //   store.dispatch('GetInfo').then(() => {
      //   })
      //   // location.reload()// 为了重新实例化vue-router对象 避免bug
      // })
      Message({
        showClose: true,
        message: res.errorCode,
        type: 'error',
        duration: 500,
        onClose: () => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        }
      });
      return Promise.reject("未登录")
    } else {
      Message({
        message: res.errorMessage,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(res)
    }
  },
  error => {
    console.error('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)
export default service

